package org.railage.client.gui.tabs;

import java.awt.Dialog.ModalityType;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.apache.log4j.Logger;
import org.railage.client.Client;
import org.railage.client.gui.dialogs.TicketSellDialog;
import org.railage.client.gui.main.GUI;
import org.railage.common.dto.TripDTO;

public class TripsTab extends AbstractTab {

	private static final long serialVersionUID = 7869887107404755908L;

	private static final Logger log = Logger.getLogger(TripsTab.class);

	private SimpleDateFormat dateTimeFormatter = new SimpleDateFormat(
			GUI.DATE_FORMAT + " " + GUI.TIME_FORMAT);

	private JTable tripTable;

	private String[] columnNames = new String[] { "Start", "Trip ID", "Route",
			"Total seats" };

	public TripsTab() {
		setLayout(null);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(0, 0, 720, 390);
		add(scrollPane);

		tripTable = new JTable();
		tripTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					int row = tripTable.rowAtPoint(e.getPoint());
					int tripID = (Integer) tripTable.getValueAt(row, 1);
					TicketSellDialog ticketDialog = new TicketSellDialog(tripID);
					ticketDialog
							.setModalityType(ModalityType.APPLICATION_MODAL);
					ticketDialog.init();
				}
			}
		});
		scrollPane.setViewportView(tripTable);
	}

	public void init() {
		Object[][] data = new Object[][] {};
		TripDTO[] trips = null;
		try {
			trips = (TripDTO[]) Client.getInstance().callMethod("getAllTrips",
					null);
			data = new Object[trips.length][];
			int i = 0;
			for (TripDTO trip : trips) {
				data[i] = new Object[] {
						dateTimeFormatter.format(trip.getStart()),
						trip.getId(), trip.getRouteName(), trip.getSeats() };
				i++;
			}
		} catch (IOException e) {
			log.error(GUI.DISCON_UNEXP_LOG_MSG, e);
			JOptionPane.showMessageDialog(this, GUI.DISCON_UNEXP_GUI_MSG);
		}
		tripTable.setModel(new DefaultTableModel(data, columnNames) {
			private static final long serialVersionUID = -4129942157856726167L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		});
	}
}
